package com.ltu.ai.sparkdesk.websocket.iat;

import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import com.google.gson.Gson;
import com.ltu.ai.sparkdesk.websocket.AiContextManager;
import com.ltu.ai.sparkdesk.websocket.legal.LegalSocketService;
import com.ltu.ai.sparkdesk.websocket.ultra.ResponSparkData.RoleContent;
import com.ltu.ai.sparkdesk.websocket.ultra.SparkSocketService;
import com.ltu.enums.SysDict;

import lombok.extern.slf4j.Slf4j;



@Slf4j
public class IatSocketClient extends WebSocketClient {
	
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
    
    private  AiContextManager.IatContext iatContext;
    private  IatSendHandle iatSendHandle;
    private  AiContextManager aiContextManager;
    private   Gson json = new Gson();
    ResponseIatData.Decoder decoder = new ResponseIatData.Decoder();
    // 开始时间
    private  Date dateBegin = new Date();
    // 结束时间
    private  Date dateEnd = new Date();
    private  SparkSocketService  sparkSocketService;
//    private  LegalSocketService  legalSocketService;
    
    public IatSocketClient(URI serverUri,AiContextManager aiContextManager,AiContextManager.IatContext iatContext,IatSendHandle iatSendHandle,SparkSocketService legalSocketService) {
    	  super(serverUri);
    	  this.iatContext = iatContext;
    	  this.iatSendHandle = iatSendHandle;
    	  this.aiContextManager = aiContextManager;
    	  this.sparkSocketService = legalSocketService;
//    	  this.legalSocketService= legalSocketService;
        if(serverUri.toString().contains("wss")){
            trustAllHosts(this);
        }
    }
    
    public static String getCurrentTimeStr() {
        return sdf.format(new Date());
    }
    
    @Override
    public void onOpen(ServerHandshake handshake) {
        System.out.println(getCurrentTimeStr() + "\t 语音识别连接建立成功！");
        iatSendHandle.sendData(this,iatContext.getFilePath());
    }
     
//  @Override
//  public void onMessage(ByteBuffer bytes) {
//      try {
//          System.out.println(getCurrentTimeStr() + "\t服务端返回：" + new String(bytes.array(), "UTF-8"));
//      } catch (UnsupportedEncodingException e) {
//          e.printStackTrace();
//      }
//  }

    @Override
    public void onMessage(String text) {
        ResponseIatData resp = json.fromJson(text, ResponseIatData.class);
        if (resp != null) {
            if (resp.getCode() != 0) {
                System.out.println( "code=>" + resp.getCode() + " error=>" + resp.getMessage() + " sid=" + resp.getSid());
                System.out.println( "错误码查询链接：https://www.xfyun.cn/document/error-code");
                return;
            }
            if (resp.getData() != null) {
            	 if (resp.getData().getResult() != null) {
                	ResponseIatData.Text te = resp.getData().getResult().getText();
                    //System.out.println(te.toString());
                        decoder.decode(te);
                        System.out.println("中间识别结果 ==》" + decoder.toString());
                }
                if (resp.getData().getStatus() == 2) {
                    // todo  resp.data.status ==2 说明数据全部返回完毕，可以关闭连接，释放资源
                    System.out.println("session end ");
                    dateEnd = new Date();
                   log.info(sdf.format(dateBegin) + "开始");
                   log.info(sdf.format(dateEnd) + "结束");
                   log.info("耗时:" + (dateEnd.getTime() - dateBegin.getTime()) + "ms");
                   String  msg = decoder.toString();
                   log.info("最终识别结果 ==》" + msg);
                   log.info("本次识别sid ==》" + resp.getSid());
//                   iatContext.getDeviceClient().getBasicRemote().sendText(decoder.toString());
                   //发送消息给前端的woebSoclit 横行 
                   String lastMsg = decoder.toString();
                   RoleContent  rc = new RoleContent(SysDict.SessionRole.Client.getName(),lastMsg,"");
                   iatContext.getHistoryList().add(rc);
                   iatContext.checkContextMax();
                   aiContextManager.responClient( iatContext.getDeviceMac(),lastMsg,SysDict.SessionRole.Client,true);
                   decoder.discard();
                   iatContext.setLegalQuestion(lastMsg);
//                   if(iatContext.getSparkSocketClient()!=null) {
////                	   legalSocketService.sendQuestion(iatContext.getLegalSocketClient(),lastMsg);
//                	   sparkSocketService.sendQuestion(iatContext.getSparkSocketClient(),lastMsg);
//                   }else {
                	   sparkSocketService.createAIClient(iatContext.getDeviceMac());
//                	   legalSocketService.createAIClient(iatContext.getDeviceMac());
//                   }
                  this.close(1000, "IAT数据接收完毕");
                } else {
                    // todo 根据返回的数据处理
//                	 aiContextManager.responClient( iatContext.getDeviceMac(),decoder.toString(),SysDict.SessionRole.Client,false);
				}
            }
        }
    }

    @Override
    public void onError(Exception e) {
    	iatContext.setIatClient(null);
        System.out.println(getCurrentTimeStr() + "\t IAT连接发生错误：" + e.getMessage() + ", " + new Date());
        e.printStackTrace();
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
    	iatContext.setIatClient(null);
        System.out.println(getCurrentTimeStr() + "\t IAT链接关闭");

    }


    public void trustAllHosts(IatSocketClient appClient) {
        System.out.println("wss");
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // TODO Auto-generated method stub

            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // TODO Auto-generated method stub

            }
        }};

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            appClient.setSocket(sc.getSocketFactory().createSocket());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}